import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

router.beforeEach(async(to, from, next) => {
  NProgress.start()
  document.title = getPageTitle(to.meta.title)
  const loginState = store.getters.loginState || false
  if (loginState && to.path === '/login') {
    next({ path: '/' })
    NProgress.done()
    return
  }
  if (!loginState && to.path !== '/login') {
    const { code, msg } = await store.dispatch('user/getAdminInfo')
    if (code === 127) {
      Message.error(msg || 'Has Error')
      next(`/login?redirect=${to.path}`)
      return
    }
    next()
    NProgress.done()
    return
  }
  next()
})

router.afterEach(() => {
  NProgress.done()
})
